package com.calsoft.Hops_Mobile_Tablet.sql;
/*
 * User: Minh Diep
 * Date: 6/24/13
 * Time: 6:27 PM
 */

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import java.io.IOException;

public class LocationDbAdapter {

    private static final String TABLE = "locationByCountries";
    public static final String ID = "_id";
    public static final String COUNTRY = "Country";
    public static final String COUNTRY_CODE = "CountryCode";
    public static final String STATE = "State";
    public static final String CITY = "City";

    private DataBaseHelper mDbHelper;
    private Context context;

    public LocationDbAdapter (Context context){
        this.context = context;
    }

    public void open() throws SQLException {
        mDbHelper = new DataBaseHelper(context);
        try {
            mDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            mDbHelper.openDataBase();
        }catch(SQLException sqle){
            throw sqle;
        }
    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor fetchAllCities() {
        return mDbHelper.queryAll(TABLE, new String[] {ID, COUNTRY, COUNTRY_CODE, STATE, CITY}, CITY);
    }

    public Cursor fetchAllRows() {
        return mDbHelper.queryAll(TABLE, new String[] {ID, COUNTRY, COUNTRY_CODE, STATE, CITY}, null);
    }

    // TODO: need to fix this
    public Cursor fetchCitiesByName(String name) {

        Cursor mCursor = null;
        if (name == null  ||  name.length() == 0) {
            mCursor = fetchAllCities();
        }
        else {
            mCursor = mDbHelper.queryRow(TABLE, new String[] {ID, COUNTRY, COUNTRY_CODE, STATE, CITY},
                    CITY + " like '%" + name + "%'", CITY + " Collate NOCASE");
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public Cursor fetchAllCitiesByCountry(String country) throws SQLException {
        Cursor mCursor =
                mDbHelper.queryRow(TABLE, new String[] {ID, COUNTRY, COUNTRY_CODE, STATE, CITY}, COUNTRY + "=\"" + country + "\"", null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}
